package cl.metlife.contentstore;

import cl.blueprintsit.utils.bdd.Closer;
import org.apache.log4j.Logger;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;

@Stateless(mappedName = "MailDAO")
@Remote(ContentRetriever.class)
@Local(ContentStore.class)
public class ContentDAO implements ContentRetriever, ContentStore {

    private Logger logger = Logger.getLogger(ContentDAO.class);

    @Override
    public void persist(String key, String content) throws ContentSavingException, RepositoryException {

        PreparedStatement preparedStatement = null;
        Connection connection = null;

        try {
            logger.debug("A punto de persistir");
            connection = getCustomConnection(); /*getConnection();*/
            String INSERT_QUERY = "INSERT INTO CONTENIDOS (LLAVE, CONTENIDO) VALUES (?,?)";

            preparedStatement = connection.prepareStatement(INSERT_QUERY);

            preparedStatement.setString(1, key);
            preparedStatement.setString(2, content);

            preparedStatement.execute();
        } catch (SQLException sql) {
            logger.error("Document not persisted: " + sql.getMessage());
            throw new ContentSavingException(sql.getMessage());
        } /*catch (NamingException e) {
            logger.error("Error obteniendo el contexto inicial.");
            throw new ContentSavingException(e.getMessage());
        }*/ finally {
            Closer.close(preparedStatement, connection);
        }
    }

    @Override
    public String getContent(String key) throws RepositoryException {

        String content = "";
        String query = "SELECT * FROM CONTENIDOS WHERE LLAVE=?";

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = getCustomConnection(); /* getConnection(); Only for testing purposes...*/
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setString(1, key);

            resultSet = preparedStatement.executeQuery();

            if(resultSet.next()) {
                content = resultSet.getString("CONTENIDO");
            }

        } catch (SQLException e) {
            throw new RepositoryException("Error in the DB: " + e.getMessage());
        } /* catch (NamingException e) {
            throw new RepositoryException("Error in the DB: " + e.getMessage());
        } */ finally {
            Closer.close(resultSet, preparedStatement, connection);
        }

        return content;
    }

    private Connection getConnection() throws SQLException, NamingException {

        Context ctx;
        DataSource ds;

        try {
            ctx = new InitialContext();
            ds = (DataSource) ctx.lookup("contentDS");
        } catch (NamingException e) {
            logger.error("The contentDS data-source was not found.");
            e.printStackTrace();
            throw e;
        }

        /* The connection is retrieved and tested */
        Connection connection = ds.getConnection();
        logger.debug("Valid connexion: " + connection);

        return connection;
    }

    /* Only for testing purposes */
    public Connection getCustomConnection() throws RepositoryException {

        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            logger.error("The PostgreSQL DBB Driver was not found.");
            throw new RepositoryException("The PostgreSQL DBB Driver was not found.");
        }

        String urlConnection = "jdbc:postgresql://127.0.0.1:5432/ContentStoreTest";
        try {
            Connection connection = DriverManager.getConnection(urlConnection, "postgres", "bpit");
            logger.debug("Connection successfully retrieved: " + connection);
            return connection;
        } catch (SQLException e) {
            throw new RepositoryException("Problem when retrieving a connection from DB: " + e.getMessage());
        }
    }
}
